<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<fmt:setBundle basename="messages.recorrido"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">

<title>GPSou</title>
<style type="text/css">
    v\:* {
      behavior:url(#default#VML);
    }
</style>

<script type="text/javascript">
//<![CDATA[

var http_request = false;

var redIcon;
var markerCurrent;
var timer=setTimeout("", 0);
var posMarkerCurrent;

var markerStart;
var markerFinish;

var dragstart=false;
var dragfinish=false;

var tramoInicial;
var tramoMedio;
var tramoFinal;
var contextmenu;

var map;
var gMarker;
var points;
var distancia;

function parseDate(str) {
  var ts=str.split(" ");
  var d=ts[0].split("-");
  var h=ts[1].split(":");
  var s=h[2].split(".");

  var fecha=new Date(Date.UTC(d[0], d[1] - 1, d[2], h[0], h[1], s[0], s[1]));

  return(fecha);
}

function center() {
    	map.panTo(new GLatLng(parent.latitudes[parent.latitudes.length-1], parent.longitudes[parent.longitudes.length-1]));
  	parent.zoomLevel=map.getZoom();
  	var centerPos=map.getCenter();
  	parent.latitud=centerPos.lat();
  	parent.longitud=centerPos.lng();

	showMap();
}

function newRoute() {
	clearTimeout(timer);

	parent.ruta=parent.ruta.slice(parent.posMarkerStart, parent.posMarkerFinish + 1);
	points=points.slice(parent.posMarkerStart, parent.posMarkerFinish + 1);
	parent.posSlice+=parent.posMarkerStart;
	parent.fechas=parent.fechas.slice(parent.posMarkerStart, parent.posMarkerFinish + 1);
	parent.latitudes=parent.latitudes.slice(parent.posMarkerStart, parent.posMarkerFinish + 1);
	parent.longitudes=parent.longitudes.slice(parent.posMarkerStart, parent.posMarkerFinish + 1);
        parent.datos="";
        for(i=0; i<parent.ruta.length; i++)
	   parent.datos=parent.datos+"#"+parent.ruta[i];

	parent.posMarkerStart=0;
	parent.posMarkerFinish=points.length - 1;

	if(parent.perfilWindow!=undefined) {
		parent.perfilWindow.close();
		parent.perfilWindow=undefined;
	}

	parent.newPath=true;
	parent.newStart=false;
	parent.newFinish=false;

    	parent.document.getElementById("lblStart").innerHTML=" ";
    	parent.document.getElementById("lblFinish").innerHTML=" ";
    	parent.document.getElementById("divNewRoute").style.display="none";

	distancia=calculaDistancia(0, points.length - 1);
parent.document.getElementById("label").innerHTML="Distancia total: <b>"+Math.round(distancia*1000)/1000+" km<\/b>";

	mapNewRoute();

	return false;
}

function mapNewRoute() {
	if(markerStart != undefined) {
		map.removeOverlay(markerStart);
		markerStart=undefined;
	}
	if(markerFinish != undefined) {
		map.removeOverlay(markerFinish);
		markerFinish=undefined;
	}
	if(markerCurrent != undefined) {
		map.removeOverlay(markerCurrent);
		markerCurrent=new GMarker(new GLatLng(0, 0), redIcon);
		map.addOverlay(markerCurrent);
	}
	if(tramoInicial != undefined)
		map.removeOverlay(tramoInicial);
	if(tramoMedio != undefined)
		map.removeOverlay(tramoMedio);
	if(tramoFinal != undefined)
		map.removeOverlay(tramoFinal);

	tramoMedio=dibujaTramo(0, points.length - 1, "#0000ff", 0.5);
	map.addOverlay(tramoMedio);
}

function fillDatos() {
      var results=parent.ruta[posMarkerCurrent].split(";");

      var fecha=parseDate(results[0]);
      var velocidad=Math.round(results[3] / 10);
      var altitud=results[5];

      parent.document.getElementById("fecha").innerHTML=fecha.toLocaleDateString();
      parent.document.getElementById("hora").innerHTML=fecha.toLocaleTimeString();
      parent.document.getElementById("velocidad").innerHTML=velocidad + " km/h";
      parent.document.getElementById("altitud").innerHTML=altitud + " m";
}

function drawMarker(position) {
	clearTimeout(timer);

	posMarkerCurrent=position;
	markerCurrent.setLatLng(new GLatLng(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent]));
	timer=window.setTimeout("fillDatos();", 1000);
}

function setPosMap(x) {
	drawMarker(x);
}

function checkPoint(point) {
	var posLat=point.lat();
	var posLng=point.lng();
	var minDst=360;
	var dst;

	var inicio=0;
	var fin=parent.ruta.length-1;

	posMarkerCurrent=inicio;
	for(i=inicio;i<=fin;i++) {
		dst=Math.abs(parent.latitudes[i] - posLat) + Math.abs(parent.longitudes[i] - posLng);
		if(dst < minDst) {
			minDst=dst;
			posMarkerCurrent=i;
		}
	}
	
	drawMarker(posMarkerCurrent);

	if(parent.perfilWindow!=undefined)
	  try {
		parent.perfilWindow.setPosProfile(posMarkerCurrent);
	  } catch(e) {
		parent.perfilWindow=undefined;
	  }
}

function dragendStart() {
	parent.posMarkerStart=posMarkerCurrent;
	markerStart.setLatLng(new GLatLng(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent]));
        parent.document.getElementById("lblStart").innerHTML=parseDate(parent.fechas[parent.posMarkerStart]).toLocaleString();
	dragstart=false;
	parent.newStart=true;
        dibujaRuta();
}

function dragendFinish() {
	parent.posMarkerFinish=posMarkerCurrent;
	markerFinish.setLatLng(new GLatLng(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent]));
        parent.document.getElementById("lblFinish").innerHTML=parseDate(parent.fechas[parent.posMarkerFinish]).toLocaleString();
	dragfinish=false;
	parent.newFinish=true;
        dibujaRuta();
}

function hideMenu() {
            contextmenu.style.visibility = "hidden";
	    GEvent.addListener(map, "mousemove", checkPoint);
            GEvent.addListener(map,"singlerightclick",showMenu);
}

function inicioRuta() {
  hideMenu();

  if(posMarkerCurrent < parent.posMarkerFinish) {
    parent.document.getElementById("divNewRoute").style.display="block";
    parent.document.getElementById("nota").style.display="none";
    parent.document.getElementById("lblStart").innerHTML=parseDate(parent.fechas[posMarkerCurrent]).toLocaleString();

    mapInicioRuta();

    parent.newStart=true;
  }
}

function mapInicioRuta() {
    if(markerStart == undefined) {
	markerStart=new GMarker(new GLatLng(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent]), {draggable: true});
	GEvent.addListener(markerStart, "dragend", dragendStart);
	GEvent.addListener(markerStart, "dragstart", function() {dragstart=true;});
	markerStart.enableDragging();
	map.addOverlay(markerStart);
    } else {
	markerStart.setLatLng(new GLatLng(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent]));
    }
    parent.posMarkerStart=posMarkerCurrent;

    dibujaRuta();
}


function finRuta() {
  hideMenu();

  if(posMarkerCurrent > parent.posMarkerStart) {
    parent.document.getElementById("divNewRoute").style.display="block";
    parent.document.getElementById("nota").style.display="none";
    parent.document.getElementById("lblFinish").innerHTML=parseDate(parent.fechas[posMarkerCurrent]).toLocaleString();

    mapFinRuta();

    parent.newFinish=true;
  }
}

function mapFinRuta() {
    if(markerFinish == undefined) {
	markerFinish=new GMarker(new GLatLng(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent]), {draggable: true});
	GEvent.addListener(markerFinish, "dragend", dragendFinish);
	GEvent.addListener(markerFinish, "dragstart", function() {dragfinish=true;});
	markerFinish.enableDragging();
	map.addOverlay(markerFinish);
    } else {
	markerFinish.setLatLng(new GLatLng(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent]));
    }
    parent.posMarkerFinish=posMarkerCurrent;

    dibujaRuta();
}

function showMenu(pixel,tile, marker) {
	  if((marker == tramoInicial) || (marker == tramoMedio) || (marker == tramoFinal) ||  (marker == markerCurrent)) {
	    if(posMarkerCurrent > parent.posMarkerFinish)
		document.getElementById("lnkStart").setAttribute("class", "disabled");
	    else 
		document.getElementById("lnkStart").setAttribute("class", "context");
	    if(posMarkerCurrent < parent.posMarkerStart)
	        document.getElementById("lnkFinish").setAttribute("class", "disabled");
	    else
	        document.getElementById("lnkFinish").setAttribute("class", "context");

            clickedPixel = pixel;
            var x=pixel.x;
            var y=pixel.y;
            if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
            if (y > map.getSize().height - 40) { y = map.getSize().height - 40 }
            var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
            pos.apply(contextmenu);
            contextmenu.style.visibility = "visible";
	    GEvent.clearListeners(map, "mousemove");
	    GEvent.clearListeners(map, "singlerightclick");
	  }
}

function load() {
   if(map == undefined) {
     var script;

     var head = document.getElementsByTagName("head")[0];
     script = document.createElement('script');
     script.type = 'text/javascript';
     script.id = 'mapLib';
     head.appendChild(script);
     script.src = "http://www.google.com/jsapi?key=ABQIAAAANdXnaDQ5-BE42sETh1OnBxQSUI96VjuXJJ7uIyuEjKZOYLINbRQ00Oj1snry5mEp_2LhV3da9mA0JQ&callback=load2";
   } else {
     showMap();
   }
}

function showMap() {
     var mapType=map.getCurrentMapType();
     if(mapType!=G_NORMAL_MAP && mapType!=G_SATELLITE_MAP && mapType!=G_HYBRID_MAP)
	map.setMapType(G_HYBRID_MAP);
     var point=new GLatLng(parent.latitud, parent.longitud);
     map.setZoom(parent.zoomLevel);
     map.panTo(point);

     if(parent.newPath) {
	points=points.slice(parent.posSlice, parent.posSlice+parent.latitudes.length);
	parent.posSlice=0;
	parent.newPath=false;
	mapNewRoute();
	parent.newPath=false;
     }
     if(parent.newStart) {
	posMarkerCurrent=parent.posMarkerStart;
	mapInicioRuta();
	parent.newStart=false;
     }
     if(parent.newFinish) {
	posMarkerCurrent=parent.posMarkerFinish;
	mapFinRuta();
	parent.newFinish=false;
     }
}

function load2() {
     google.load("maps", "2", {"callback" : init});
}

function init() {
     var script;
     var head = document.getElementsByTagName("head")[0];
     script = document.createElement('script');
     script.type = 'text/javascript';
     script.id = 'pano1';
     head.appendChild(script);
     script.src = "../scripts/markermanager.js";

     script = document.createElement('script');
     script.type = 'text/javascript';
     script.id = 'pano2';
     head.appendChild(script);
     script.src = "../scripts/pano_layer.js";

     script = document.createElement('script');
     script.type = 'text/javascript';
     script.id = 'pano3';
     head.appendChild(script);
     script.src = "../scripts/pano_maptypecontrol.js";

     script = document.createElement('script');
     script.type = 'text/javascript';
     script.id = 'encoder';
     head.appendChild(script);
     script.src = "../scripts/PolylineEncoder.js";

    var url="/VEGPS/ServletGoogleGPS?p=getRuta&desde="+parent.desde+"&hasta="+parent.hasta;
	
	contextmenu = document.createElement("div");
	contextmenu.style.visibility="hidden";
	contextmenu.style.background="#ffffff";
	contextmenu.style.border="1px solid #8888FF";

	contextmenu.innerHTML = '<a href="javascript:inicioRuta()"><div id="lnkStart" class="context">&nbsp;&nbsp;<fmt:message key="limits.link.1"/>&nbsp;&nbsp;</div></a>'
		+ '<a href="javascript:finRuta()"><div id="lnkFinish" class="context">&nbsp;&nbsp;<fmt:message key="limits.link.2"/>&nbsp;&nbsp;</div></a>';

	if(parent.datos == undefined) {
          if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
            }
          } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
                 } catch (e) {}
            }
          }

          if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
          }
          http_request.onreadystatechange = alertContents;
          http_request.open('GET', url, true);
          http_request.send(null);
	} else {
	  loadMaps();
	}
}

function switchMap() {
  parent.zoomLevel=map.getZoom();
  var centerPos=map.getCenter();
  parent.latitud=centerPos.lat();
  parent.longitud=centerPos.lng();
  parent.document.getElementById("VE").style.display="block";
  parent.document.getElementById("GM").style.display="none";
  parent.WIN=parent.frames['VE'];
  parent.VE.load();
}

function alertContents() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {

            parent.datos=http_request.responseText;
    	    parent.ruta=parent.datos.split("#");
	    parent.ruta.shift();

	    if(parent.ruta.length<=0) {
	    	alert("No hay datos de recorrido en el intervalo de tiempo seleccionado");
		history.back(1);
	    } else {
		parent.posMarkerFinish=parent.ruta.length-1;

		loadMaps();
	    }
        } else {
            alert('Se ha producido un error al obtener la ruta.');
	    history.back(1);
        }
    }
}

function loadMaps() {
    if(typeof(PanoMapTypeControl)=="undefined") {
	window.setTimeout("loadMaps();", 100);
	return;
    }

    if (GBrowserIsCompatible()) {
        parent.document.getElementById("espera").style.display="none";
        parent.document.getElementById("pagina").style.display="block";

     	if(parent.newPath) {
	    points=points.slice(parent.posSlice, parent.posSlice+parent.latitudes.length);
	    parent.posSlice=0;
	    parent.newPath=false;
	    mapNewRoute();
	    parent.newPath=false;
	}

        var baseIcon = new GIcon();
        baseIcon.iconSize=new GSize(8,8);
        baseIcon.iconAnchor=new GPoint(4,4);
        baseIcon.infoWindowAnchor=new GPoint(4,0);
        redIcon = (new GIcon(baseIcon, "/VEGPS/html/images/redSquare.png", null, ""));

	map = new GMap2(document.getElementById("map"));
	points=[];

	markerCurrent=new GMarker(new GLatLng(0, 0), redIcon);

	map.addMapType(G_SATELLITE_3D_MAP);
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(0, 0), 13);
	map.addControl(new PanoMapTypeControl());
	map.enableScrollWheelZoom();
	map.enableContinuousZoom();
	map.setMapType(G_HYBRID_MAP);


	map.getContainer().appendChild(contextmenu);

	GEvent.addListener(map, "click", hideMenu);
	GEvent.addListener(map, "dragstart", hideMenu);
        GEvent.addListener(map,"singlerightclick",showMenu);

        tramoMedio=dibuja();
	map.addOverlay(tramoMedio);
	map.addOverlay(markerCurrent);
	distancia=calculaDistancia(0, parent.ruta.length-1);
	parent.document.getElementById("label").innerHTML="<fmt:message key="distance.text"/> <b>"+Math.round(distancia*1000)/1000+" km<\/b>";

	GEvent.addListener(map, "mousemove", checkPoint);

	window.setTimeout("center();", 10);
    }
}

function dibujaRuta() {
	if(tramoInicial != undefined)
		map.removeOverlay(tramoInicial);
	if(tramoMedio != undefined)
		map.removeOverlay(tramoMedio);
	if(tramoFinal != undefined)
		map.removeOverlay(tramoFinal);
	tramoInicial=dibujaTramo(0, parent.posMarkerStart, "#ff0000", 0.5);
	tramoMedio=dibujaTramo(parent.posMarkerStart, parent.posMarkerFinish, "#0000ff", 0.5);
	tramoFinal=dibujaTramo(parent.posMarkerFinish, parent.ruta.length - 1, "#ff0000", 0.5);

	if(tramoInicial!=undefined)
	  map.addOverlay(tramoInicial);
	if(tramoMedio!=undefined)
	  map.addOverlay(tramoMedio);
	if(tramoFinal!=undefined)
	  map.addOverlay(tramoFinal);
}

function dibujaTramo(startPoint, finishPoint, color, weight) {
    var polylineRuta;

    if(finishPoint > startPoint) {
      var polylineEncoder=new PolylineEncoder(18, 2, 0.00001, true);
      polylineRuta=polylineEncoder.dpEncodeToGPolyline(points.slice(startPoint, finishPoint+1), color, 5, weight);
    } else if(finishPoint == startPoint)
      polylineRuta=new GPolyline(points.slice(startPoint, finishPoint+1), color, 5, weight, {clickable: true});

    return(polylineRuta);
}

function dibuja() {
    if(typeof(PolylineEncoder)=="undefined") {
        window.setTimeout("dibuja();", 100);
        return;
    }

    var point;
    var latitud, longitud, latitudNMEA, longitudNMEA;
    var grados;
    var polylineRuta;
    var results;

    try {
      parent.fechas = new Array(parent.ruta.length);
      parent.latitudes = new Array(parent.ruta.length);
      parent.longitudes = new Array(parent.ruta.length);

      for(i=0; i<parent.ruta.length; i++) {
        results=parent.ruta[i].split(";");

        latitudNMEA=results[1];
        longitudNMEA=results[2];

        grados=Math.floor(latitudNMEA/1000000);
        if(grados<0)
	  grados=grados+1;
        latitud=(latitudNMEA/1000000-grados)/0.6+grados;
        grados=Math.floor(longitudNMEA/1000000);
        if(grados<0)
	  grados=grados+1;
        longitud=(longitudNMEA/1000000-grados)/0.6+grados;

	parent.fechas[i]=results[0];
	parent.latitudes[i]=latitud;
	parent.longitudes[i]=longitud;

        point = new GLatLng(latitud, longitud);
        points.push(point);
      }

      var polylineEncoder=new PolylineEncoder(18, 2, 0.00001, true);
      if(points.length > 1)
        polylineRuta=polylineEncoder.dpEncodeToGPolyline(points, "#0000ff", 5, 0.5);
      else
        polylineRuta=new GPolyline(points, "#0000ff", 5, 0.5, {clickable: true});

    } catch (err) {alert("ERROR: "+err.description);}

    return(polylineRuta);
}

function calculaDistancia(startPoint, finishPoint) {
    var dx, dy;

    var dst=0;
    for(i=startPoint+1;i<=finishPoint;i++) {
        dx=6370*(parent.latitudes[i]-parent.latitudes[i-1])*Math.PI/180;
        dy=6370*Math.cos(parent.latitudes[i]*Math.PI/180)*(parent.longitudes[i]-parent.longitudes[i-1])*Math.PI/180;
        dst+=Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2));
    }
    return(dst);
}

function unload() {
  GUnload();
}
//]]>
</script>

</head>

<body onunload="unload()">
  <div id="map" style="width: 500px; height: 300px"></div>
</body>

</html>


